package br.com.puc.controllers;

import java.util.List;

import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Put;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.puc.models.Orientacao;
import br.com.puc.models.annotations.Publico;
import br.com.puc.repositories.AlunoRepository;
import br.com.puc.repositories.OrientacaoRepository;
import br.com.puc.repositories.ProfessorRepository;

@Resource
public class OrientacaoController {

	private final Result result;
	private final OrientacaoRepository repository;
	
	private final Validator validator;
	private ProfessorRepository professorRepository;
	private AlunoRepository alunoRepository;
	
	public OrientacaoController(Result result, OrientacaoRepository repository, ProfessorRepository professorRepository, 
	AlunoRepository alunoRepository, Validator validator) {
		this.result = result;
		this.repository = repository;
		this.professorRepository = professorRepository;
		this.alunoRepository = alunoRepository;
	
		this.validator = validator;
	}

	@Publico
	@Get("/orientacoes")
	public List<Orientacao> index() {
		return repository.findAll();
	}
	
	@Post("/orientacoes")
	public void create(Orientacao orientacao) {
		validator.validate(orientacao);
		validator.onErrorUsePageOf(this).newOrientacao();
		repository.create(orientacao);
		result.redirectTo(this).index();
	}
	
	@Get("/orientacoes/new")
	public Orientacao newOrientacao() {
		result.include("professores", professorRepository.findAll());
		result.include("alunos", alunoRepository.findAll());
		return new Orientacao();
	}
	
	@Put("/orientacoes")
	public void update(Orientacao orientacao) {
		validator.validate(orientacao);
		validator.onErrorUsePageOf(this).edit(orientacao);
		repository.update(orientacao);
		result.redirectTo(this).index();
	}
	
	@Get("/orientacoes/{orientacao.id}/edit")
	public Orientacao edit(Orientacao orientacao) {
		result.include("professores", professorRepository.findAll());
		result.include("alunos", alunoRepository.findAll());
		return repository.find(orientacao.getId());
	}

	@Publico
	@Get("/orientacoes/{orientacao.id}")
	public Orientacao show(Orientacao orientacao) {
		return repository.find(orientacao.getId());
	}

	@Delete("/orientacoes/{orientacao.id}")
	public void destroy(Orientacao orientacao) {
		repository.destroy(repository.find(orientacao.getId()));
		result.redirectTo(this).index();  
	}
}
